package com.songcha.module_bookreader.service

import android.app.Service
import android.content.Intent
import android.os.Binder
import android.os.IBinder
import com.songcha.module_bookreader.api.BookReaderApiManager
import com.songcha.module_bookreader.bean.book.BookChapterContentDataBean
import com.songcha.module_bookreader.manager.CacheManager
import com.songcha.module_bookreader.utils.FileUtils
import com.songcha.module_bookreader.utils.StringUtils
import com.songcha.library_business.bean.book.BookBean
import com.songcha.library_business.bean.book.BookChapterCatalogBean
import com.songcha.library_business.event.book.BookDownloadCompleteEvent
import com.songcha.library_business.event.book.BookDownloadErrorEvent
import com.songcha.library_business.event.book.BookDownloadingEvent
import com.songcha.library_business.proxy.database.BookDownloadDaoManager
import com.songcha.library_business.util.BookFileUtil
import com.songcha.library_common.util.LogUtil
import com.songcha.library_common.util.ToastUtil
import io.reactivex.Observable
import io.reactivex.Observer
import io.reactivex.disposables.Disposable
import io.reactivex.functions.Function
import io.reactivex.schedulers.Schedulers
import org.greenrobot.eventbus.EventBus
import org.json.JSONArray
import org.json.JSONObject
import java.io.File

class BookDownloadService:Service() {
    private var book=BookBean()
    private var chapterList=mutableListOf<BookChapterCatalogBean.DataBean>()
    private var isDownloading=false

    override fun onBind(intent: Intent?): IBinder? {
        return MyBinder()
    }

    class BookDownloadInfo(val chapter:Int,val chapterId:Int,val content:String){

    }

    inner class MyBinder: Binder(){
        fun startDownload(book:BookBean,chapterList:MutableList<BookChapterCatalogBean.DataBean>){
            if(chapterList.size==0){
                ToastUtil.show("没有书籍章节信息")
                return
            }
            if(isDownloading){
                ToastUtil.show("请等待当前书籍缓存完成")
                return
            }

            this@BookDownloadService.book=book
            this@BookDownloadService.chapterList=chapterList
            isDownloading=true

            ToastUtil.show("开始缓存书籍,共${chapterList.size}个章节")

            //保存章节信息
            val chapterArr=JSONArray()
            for(item in chapterList){
                val chapterItem=JSONObject()
                chapterItem.put("id",item.id)
                chapterItem.put("bookId",item.bookId)
                chapterItem.put("chapterId",item.chapterId)
                chapterItem.put("chapterTitle",item.chapterTitle)
                chapterItem.put("isVip",item.isVip)
                chapterItem.put("words",item.words)
                chapterItem.put("displayOrder",item.displayOrder)
                chapterItem.put("updateTime",item.updateTime)
                chapterArr.put(chapterItem)
            }
            val chapterData=JSONObject()
            chapterData.put("code",200)
            chapterData.put("msg","")
            chapterData.put("data",chapterArr)


            val chapterFile=File(BookFileUtil.getBookFilePath(book.id)+"chapter.json")
            if(!chapterFile.exists())
                FileUtils.createFile(chapterFile)
            FileUtils.writeFile(chapterFile.absolutePath, StringUtils.formatContent(chapterData.toString()), false)

            val list= mutableListOf<Observable<BookChapterContentDataBean>>()
            var start=0

            //从之前下载章节继续下载
            val file= BookFileUtil.getBookFile(book.id)
            if(file.exists() && file.isDirectory){
                val fileList=file.listFiles()
                if(fileList!=null){
                    for(i in 0 until fileList.size){
                        val item=fileList[i]
                        if(item.name.endsWith(".txt") && item.length()>0){
                            try{
                                val alreadyDownloadChapter=item.name.substring(0,item.name.length-4).toInt()
                                if(alreadyDownloadChapter>start)
                                    start=alreadyDownloadChapter-1
                            }catch (e:Exception){
                                e.printStackTrace()
                            }
                        }else{
                            break
                        }
                    }
                }
            }

            for(i in start until chapterList.size){
                val item=chapterList[i]
                val obs=BookReaderApiManager.api.getBookChapterContent(item.chapterId)
                list.add(obs)
            }

            var downloadCount=0

            Observable.create<BookDownloadInfo> {
                for(i in list.indices){
                    val item=list[i]
                    item.subscribeOn(Schedulers.single())
                        .observeOn(Schedulers.computation())
                        .map (object :Function<BookChapterContentDataBean,BookDownloadInfo>{
                            override fun apply(t: BookChapterContentDataBean): BookDownloadInfo {
                                return BookDownloadInfo(i+1+start,t.data.chapterId,t.data.content)
                            }
                        })
                        .subscribe(object :Observer<BookDownloadInfo>{
                            override fun onSubscribe(d: Disposable) {

                            }

                            override fun onError(e: Throwable) {
                                it.onError(e)
                            }

                            override fun onComplete() {

                            }

                            override fun onNext(t: BookDownloadInfo) {
                                it.onNext(t)
                                if(i==list.size-1){
                                    LogUtil.log("${book.bookName}书籍缓存完成")
                                    it.onComplete()
                                }
                            }

                        })


                }


                //it.onNext("")
               // it.onComplete()

            }.subscribeOn(Schedulers.io())
                .observeOn(Schedulers.newThread())
                .subscribe(object :Observer<BookDownloadInfo>{
                    override fun onSubscribe(d: Disposable) {

                    }

                    override fun onError(e: Throwable) {
                        //LogUtil.log("aaa","onError")
                        isDownloading=false
                        EventBus.getDefault().post(BookDownloadErrorEvent(book,e))
                    }

                    override fun onComplete() {
                        isDownloading=false
                        ToastUtil.show("书籍《"+book.bookName+"》缓存完成")
                        EventBus.getDefault().post(BookDownloadCompleteEvent(book))
                        //下载完成添加到已缓存数据库
                        BookDownloadDaoManager.addBookDownload(book.id)
                    }

                    override fun onNext(t: BookDownloadInfo) {
                       //LogUtil.log("aaa","onNext")
                        if(t.content.isNotBlank()){
                            downloadCount++
                            LogUtil.log("已缓存${downloadCount}章",t.chapter,t.chapterId)
                            CacheManager.getInstance().saveChapterFile(book.id, t.chapter, t.content,true)
                        }
                        EventBus.getDefault().post(BookDownloadingEvent(book, t.chapter,chapterList.size))
                    }

                })

        }
    }





}